package com.cmd.project.service.impl;

import java.util.List;

import com.cmd.common.exception.ServiceException;
import com.cmd.common.utils.DateUtils;
import com.cmd.common.utils.SecurityUtils;
import com.cmd.common.utils.StringUtils;
import com.cmd.project.vo.StudentRegistrationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cmd.project.mapper.StudentRegistrationMapper;
import com.cmd.project.domain.StudentRegistration;
import com.cmd.project.service.IStudentRegistrationService;

/**
 * 学生报名信息Service业务层处理
 *
 * @author cq
 * @date 2025-04-02
 */
@Service
public class StudentRegistrationServiceImpl implements IStudentRegistrationService {
    @Autowired
    private StudentRegistrationMapper studentRegistrationMapper;

    /**
     * 查询学生报名信息
     *
     * @param id 学生报名信息主键
     * @return 学生报名信息
     */
    @Override
    public StudentRegistration selectStudentRegistrationById(Long id) {
        return studentRegistrationMapper.selectStudentRegistrationById(id);
    }

    /**
     * 查询学生报名信息列表
     *
     * @param studentRegistration 学生报名信息
     * @return 学生报名信息
     */
    @Override
    public List<StudentRegistration> selectStudentRegistrationList(StudentRegistration studentRegistration) {
        return studentRegistrationMapper.selectStudentRegistrationList(studentRegistration);
    }

    /**
     * 新增学生报名信息
     *
     * @param studentRegistration 学生报名信息
     * @return 结果
     */
    @Override
    public int insertStudentRegistration(StudentRegistration studentRegistration) {
        try {
            String username = SecurityUtils.getUsername();
            studentRegistration.setCreateBy(username);
        } catch (Exception e) {
           e.printStackTrace();
        }
        studentRegistration.setCreateTime(DateUtils.getNowDate());
        studentRegistration.setCompetitionNumber(System.currentTimeMillis()+"");
        return studentRegistrationMapper.insertStudentRegistration(studentRegistration);
    }

    /**
     * 修改学生报名信息
     *
     * @param studentRegistration 学生报名信息
     * @return 结果
     */
    @Override
    public int updateStudentRegistration(StudentRegistration studentRegistration) {
        studentRegistration.setUpdateTime(DateUtils.getNowDate());
        return studentRegistrationMapper.updateStudentRegistration(studentRegistration);
    }

    /**
     * 批量删除学生报名信息
     *
     * @param ids 需要删除的学生报名信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentRegistrationByIds(Long[] ids) {
        return studentRegistrationMapper.deleteStudentRegistrationByIds(ids);
    }

    /**
     * 删除学生报名信息信息
     *
     * @param id 学生报名信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentRegistrationById(Long id) {
        return studentRegistrationMapper.deleteStudentRegistrationById(id);
    }

    @Override
    public String importStudentRegistration(List<StudentRegistrationVo> registrationList) {
        if (StringUtils.isNull(registrationList) || registrationList.size() == 0) {
            throw new ServiceException("导入学生报名数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (StudentRegistrationVo registrationVo : registrationList) {
            try {
                // 验证必要字段
                if (StringUtils.isEmpty(registrationVo.getName()) || StringUtils.isEmpty(registrationVo.getIdNumber())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生姓名和身份证不能为空，导入失败");
                    continue;
                }
                
                // 构造学生报名信息实体
                StudentRegistration registration = new StudentRegistration();
                registration.setName(registrationVo.getName());
                registration.setIdNumber(registrationVo.getIdNumber());
                registration.setCompetitionGroup(registrationVo.getCompetitionGroup());
                registration.setCompetitionNumber(registrationVo.getCompetitionNumber());
                String preliminaryReview = registrationVo.getPreliminaryReview();
                String convertedValue = "通过".equals(preliminaryReview) ? "3" :
                        "不通过".equals(preliminaryReview) ? "2" : "1";
                registration.setPreliminaryReview(convertedValue);

                String firstReview = registrationVo.getFirstReview();
                String firstReviewValue = "通过".equals(firstReview) ? "3" :
                        "不通过".equals(firstReview) ? "2" : "1";
                registration.setFirstReview(firstReviewValue);
                String finalReview = registrationVo.getFinalReview();
                String finalReviewValue = "通过".equals(finalReview) ? "3" :
                        "不通过".equals(finalReview) ? "2" : "1";
                registration.setFinalReview(finalReviewValue);
                registration.setAward(registrationVo.getAward());
                
                // 设置更新者
                try {
                    String username = SecurityUtils.getUsername();
                    registration.setUpdateBy(username);
                } catch (Exception e) {
                    registration.setUpdateBy("");
                }
                registration.setUpdateTime(DateUtils.getNowDate());
                
                // 根据身份证、参赛组别和参赛编号查询是否已存在该学生信息
                StudentRegistration existingRegistration = studentRegistrationMapper.selectStudentRegistrationByIdNumberAndGroupAndNumber(
                    registration.getIdNumber(), 
                    registration.getCompetitionGroup(), 
                    registration.getCompetitionNumber()
                );
                
                if (existingRegistration != null) {
                    // 如果存在，则更新记录
                    registration.setId(existingRegistration.getId());
                    int result = studentRegistrationMapper.updateStudentRegistration(registration);
                    if (result > 0) {
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学生 " + registration.getName() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、学生 " + registration.getName() + " 更新失败");
                    }
                } else {
                    // 如果不存在，则记录为更新失败
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + registration.getName() + " 不存在，无法更新");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + registrationVo.getName() + " 更新失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，更新失败！共 " + failureNum + " 条数据更新失败，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部更新成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}